<%--
  Created by IntelliJ IDEA.
  User: 兀兀
  Date: 2019/11/22
  Time: 16:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/commonPage/common.jsp"%>
<html>
<head>
    <title>联盟成员管理</title>
</head>
<body style="overflow: hidden;">

<div id="popupWin" class="layui-form" style="display: none; padding: 20px;">

        <div style="height: 200px; ">
            <div style="height: 100%; width: 35%; float: left;">
                <a style="display: none;" id="id"></a>
                <div class="layui-form-item" style="height: 60px; line-height: 100px;">
                    <label class="layui-form-label">密码<font  color="#ff0000">*</font></label>
                    <div class="layui-input-inline">
                        <input type="text" id="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item" style="height: 60px; line-height: 100px;">
                    <label class="layui-form-label">职位<font  color="#ff0000">*</font></label>
                    <div class="layui-input-inline">
                        <input type="text" id="position" placeholder="职位" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item" style="height: 60px; line-height: 100px;">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-form layui-input-inline">
                        <select name="gride" id="gride" lay-filter="myselect">
                            <option value="管理员" selected="selected">管理员</option>
                            <option value="超级管理员">超级管理员</option>
                        </select>
                    </div>
                </div>



            </div>
            <div style="height: 100%; width: 35%; float: left;">
                <div class="layui-form-item" style="height: 60px; line-height: 100px;">
                    <label class="layui-form-label">名称<font  color="#ff0000">*</font></label>
                    <div class="layui-input-inline">
                        <input type="text" id="name" placeholder="名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item" style="height: 60px; line-height: 100px;">
                    <label class="layui-form-label">加入时间<font  color="#ff0000">*</font></label>
                    <div class="layui-input-inline">
                        <input type="text" id="join_time" placeholder="加入时间" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div style="height: 100%; width: 30%; float: left;">
                <div style="border: solid 1px #000; width: 80%; height: 100%;" id="img_div">
                    <img src="" id="logo_url" style="width: 100%; height: 100%;">
                </div>
            </div>
        </div>
        <div class="layui-form-item layui-form-text" style="margin-top: 20px;">
            <label class="layui-form-label">介绍</label>
            <div class="layui-input-block">
                <textarea placeholder="介绍" id="context" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input type="text" name="title" id="remark" autocomplete="off" placeholder="备注" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" id="role_div_continer" style="overflow: hidden">
            <label class="layui-form-label">权限管理</label>
            <div id="role-div" style="margin-top: 10px;"></div>
        </div>

</div>

<%--顶部工具栏--%>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-bg-blue" lay-event="addBtn">添加</button>
        <button class="layui-btn layui-btn-sm layui-bg-red" lay-event="deleteBtn">删除</button>
    </div>
</script>
<div style="width: 100%; height: 100%; background: #fff;">	
	<table class="layui-hide" id="center-table" lay-filter="center-table" style="height: 100%; overflow: hidden; "></table>
</div>
</body>
<script>
    var loadIndex;
    var transfer;
    layui.use(['table','upload','transfer','form','laydate','element'], function(){
        var upload = layui.upload;
        var table = layui.table;
        var laydate = layui.laydate;
        var element = layui.element;
        var form = layui.form;
        transfer = layui.transfer;
        form.render();
        //日期
        laydate.render({
            elem: '#join_time'
        });

        table.render({
            elem: '#center-table'
            ,type:"post"
            ,toolbar:"#toolbar"
            ,url:'${base}/adminController/listAdmin'
            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页
                ,position:'bottom'
            }
            ,height: $(document).height() - $('#center-table').offset().top - 20
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'username', title: '用户名',event : 'detial', sort: true ,align: 'center' , fixed: 'left'}
                ,{field:'position', title: '职位',event : 'detial', sort: true}
                ,{field:'joinTime', title: '加入时间',event : 'detial', sort: true,templet: "<div>{{layui.util.toDateString(d.application_end_time, 'yyyy-MM-dd')}}</div>"}
                // ,{field:'context', title: '成员介绍'}
                ,{field:'gride', title: '管理员级别',event : 'detial', sort: true}
                // ,{field:'logoUrl', title: '头像'}
                ,{field:'remark', title: '备注'}
            ]]
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "count": res.total, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
        });

        //头工具栏事件
        table.on('toolbar(center-table)', function(obj){
            switch (obj.event) {
                case "addBtn":
                    $("#id").val("");
                    $("#password").val("");
                    $("#name").val("");
                    $("#context").val("");
                    $("#join_time").val("");
                    $("#position").val("");
                    $("#remark").val("");
                    var isSaveing = false;
                    $("#role_div_continer").height('0');
                    layer.open({
                        type: 1,
                        title:'添加'
                        ,area: '60%',//['60%','60%'],
                        content: $("#popupWin"),  //弹出窗口
                        btn:['添加','取消'],
                        yes: function (index, layero) {
                            if($("#password").val()=="" || $("#name").val()==""||$("#join_time").val()==""||$("#position").val()=="" ){
                                layer.msg("请输入必要信息！")
                            }else{
                            var loading =layer.load(0, {
                                shade: false,
                                time: 2*1000
                            });
                            if (!isSaveing){
                                isSaveing=true;
                                $.ajax({
                                    type: "post",
                                    dataType: "json",
                                    url: '${base}/adminController/addAdminFunc',
                                    data: {
                                    	password:$("#password").val(),
                                        username:$("#name").val(),
                                        logoUrl:$("#logo_url").attr('src'),
                                        context:$("#context").val(),
                                        gride:$("#gride").val(),
                                        joinTime:$("#join_time").val(),
                                        position:$("#position").val(),
                                        remark:$("#remark").val()
                                    },
                                    success: function (data) {
                                        isSaveing=false;
                                        if(data.result){
                                            layer.close(loading);
                                            layer.msg("添加成功！");
                                            layer.close(index);
                                            table.reload("center-table");

                                        }else{
                                            layer.msg(data.message);
                                        }
                                    }
                                })
                            }
                            }
                        }
                    });break;
                case "deleteBtn":
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    var ids = new Array();
                    data.forEach(function(n,i){
                        ids.push(n.id);
                    });
                    if (ids!=''){
                        layer.msg('是否删除所有与该用户相关信息？', {
                            time: 20000, //20s后自动关闭
                            btn: ['确定', '取消'],
                            yes:function(){
                                $.ajax({
                                    type: "post",
                                    dataType: "json",
                                    url: '${base}/adminController/deleteAdminFunc',
                                    data: {
                                        ids:ids
                                    },
                                    success: function (data) {
                                        if(data.result){
                                            layer.msg("删除成功！");
                                            table.reload("center-table");
                                        }else{
                                            layer.msg(data.message);
                                        }
                                    }
                                })
                            }
                        });
                    }else{
                        layer.msg("请选择需要删除的行！");
                    }


                    break;
            }

        });


        //渲染穿梭框
        transfer.render({
            elem: '#role-div'  //绑定元素
            ,data: []
            ,id: 'roleTransfer' //定义索引 重载时可以用到
        });



        //监听单元格事件
        table.on('tool(center-table)', function(obj) {
            var data = obj.data;
            if (obj.event === 'detial') {
                $("#role_div_continer").height('auto');
                //加载下拉菜单
                loadUserRole(data.uid);
                form.render('checkbox');
                var data = obj.data;
                $("#id").val(data.id);
                $("#password").val('');
                $("#name").val(data.username);
                $("#context").val(data.context);
                $("#logo_url").attr('src','');
                $("#logo_url").attr('src',data.logoUrl);
                $("#gride").val(data.gride);
                $("#join_time").val(dateFormat(data.joinTime));
                $("#position").val(data.position);
                $("#remark").val(data.remark);
                $("#uid").attr('readOnly','readOnly');
                layer.open({
                    type: 1,
                    title:'详细信息'
                    ,area: ['100%','100%'],//['60%','60%'],
                    content: $("#popupWin"),  //弹出窗口
                    btn:['修改','关闭'],
                    yes: function (index, layero) {
                        $.ajax({
                            type: "post",
                            dataType: "json",
                            url: '${base}/adminController/updateAdminFunc',
                            data: {
                                id:$("#id").val(),
                                password:$("#password").val(),
                                username:$("#name").val(),
                                context:$("#context").val(),
                                logoUrl:$("#logo_url").attr('src'),
                                gride:$("#gride").val(),
                                joinTime:$("#join_time").val(),
                                position:$("#position").val(),
                                remark:$("#remark").val()
                            },
                            success: function (data) {
                                if(data.result){
                                    layer.msg("修改成功！");
                                    layer.close(index);
                                    table.reload("center-table");
                                }else{
                                    layer.msg(data.message);
                                }
                            }
                        })

                    }
                });
            }
        })

        //图片上传方法
        var uploadInst = upload.render({
            elem: '#img_div' //绑定元素
            ,url: '${base}/fileUpload' //上传接口
            ,accept: 'images' //允许上传的文件类型
            ,acceptMime:'image/*'
            ,size: 2000 //最大允许上传的文件大小 200kb
            ,multiple:false//是否允许多文件上传
            ,before:function () {
                loadIndex = LoadWait("正在上传。。。");
            }
            ,done: function(res){
                layer.closeAll(loadIndex);
                //上传完毕回调
                if (res.result){
                    layer.msg("上传成功！"+res.message);
                    $("#logo_url").attr('src',res.message)
                }else{
                    layer.msg("上传失败！");
                }
            }
            ,error: function(){
                layer.msg("图片上传失败！")
                //请求异常回调
            }
        });

    });

    function loadUserRole(user_id) {
        var roleSouce;
        var choseValue;
        $.ajax({
            type: "post",
            dataType: "json",
            url: '${base}/admin/menu/getAllMenuList',
            async:false,//改为同步请求，防止页面加载与数据渲染的顺序被颠倒
            success: function (data) {
                roleSouce = data;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: '${base}/admin/menu/getUserMenuByUserId',
                    async:false,//改为同步请求，防止页面加载与数据渲染的顺序被颠倒
                    data:{
                        "user_id":user_id
                    },
                    success: function (data) {
                        choseValue=data;
                    }
                });
            }

        });
        var ids = new Array();
        if (choseValue!=null){
            for (var i=0;i<choseValue.length;i++){
                ids[i] = (choseValue[i].id);
            }
        }
        transfer.reload('roleTransfer',{
            title:['禁止权限', '允许权限'],
            data:roleSouce,
            value:ids,
            parseData: function(res){
                return {
                    "value": res.id //数据值
                    ,"title": res.menuName //数据标题
                    ,"disabled": res.disabled  //是否禁用
                    ,"checked": res.checked //是否选中
                }
            },
            onchange: function(data, index){
                var menu_ids = new Array();
                for (var i=0;i<data.length;i++){
                    menu_ids[i]=data[i].value;
                }
                console.log(menu_ids);
                if (index==0){
                    //授权
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: '${base}/admin/roles/insertMenus',
                        async:false,//改为同步请求，防止页面加载与数据渲染的顺序被颠倒
                        data:{
                            "user_id":user_id,
                            "menu_ids":menu_ids
                        }
                    });
                }else{
                    //取消授权
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: '${base}/admin/roles/deleteMenus',
                        async:false,//改为同步请求，防止页面加载与数据渲染的顺序被颠倒
                        data:{
                            "user_id":user_id,
                            "menu_ids":menu_ids
                        }
                    });
                }
            }
        });
    }

</script>
</html>
